<template>
  <div class="login-container">
    <div class="login-card">
      <h2>在线客服登录</h2>

      <!-- 合并登录方式到同一页面 -->
      <div class="login-options">
        <!-- 匿名登录选项 -->
        <div class="login-option anonymous-option">
          <div class="option-header">
            <span class="option-icon">
              <i class="fa fa-user-secret"></i>
            </span>
            <h3>匿名聊天</h3>
          </div>
          <p class="option-desc">无需注册，直接开始聊天</p>
          <button @click="handleAnonymousLogin" class="option-btn">进入聊天</button>
        </div>

        <div class="divider">或者</div>

        <!-- 手机号登录选项 -->
        <div class="login-option phone-option">
          <div class="option-header">
            <span class="option-icon">
              <i class="fa fa-mobile"></i>
            </span>
            <h3>手机号登录</h3>
          </div>

          <form @submit.prevent="handlePhoneLogin" class="phone-form">
            <div class="form-group">
              <input
                  type="tel"
                  v-model="phone"
                  placeholder="请输入手机号"
                  required
                  pattern="^1[3-9]\d{9}$"
                  class="phone-input"
              >
            </div>

            <div class="form-group code-group">
              <input
                  type="text"
                  v-model="code"
                  placeholder="请输入验证码"
                  required
                  class="code-input"
              >
              <button
                  type="button"
                  class="get-code-btn"
                  @click="sendCode"
                  :disabled="isSendingCode"
              >
                {{ isSendingCode ? `${countdown}s后重发` : '获取验证码' }}
              </button>
            </div>

            <button type="submit" class="option-btn phone-login-btn">登录并聊天</button>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';

const router = useRouter();
const store = useStore();

// 登录状态管理
const phone = ref('');
const code = ref('');
const isSendingCode = ref(false);
const countdown = ref(60);

// 发送验证码
const sendCode = () => {
  if (!phone.value || !/^1[3-9]\d{9}$/.test(phone.value)) {
    alert('请输入正确的手机号');
    return;
  }

  isSendingCode.value = true;

  // 调用后端发送验证码接口
  const { $axios } = require('@/main').default.config.globalProperties;
  $axios.post('/user/auth/code', { phone: phone.value })
      .then(() => {
        alert('验证码发送成功');

        // 倒计时
        const timer = setInterval(() => {
          countdown.value--;
          if (countdown.value <= 0) {
            clearInterval(timer);
            isSendingCode.value = false;
            countdown.value = 60;
          }
        }, 1000);
      })
      .catch(err => {
        console.error('发送验证码失败', err);
        alert('发送验证码失败，请重试');
        isSendingCode.value = false;
      });
};

// 匿名登录
const handleAnonymousLogin = () => {
  const { $axios } = require('@/main').default.config.globalProperties;
  $axios.post('/user/anonymous/login')
      .then(res => {
        const { token, user } = res.data.data;
        if (user && user.id) {
          // 调用创建会话接口获取sessionId
          $axios.post('/user/session', null, {
            params: { userId: user.id }
          }).then(sessionRes => {
            const sessionId = sessionRes.data.data.id;
            store.dispatch('setUserInfo', {
              userId: user.id,
              sessionId,
              token  // 存储token
            });
            router.push('/user/chat');
          });
        } else {
          alert('登录失败，未获取到用户信息');
        }
      })
      .catch(err => {
        console.error('匿名登录失败', err);
        alert('登录失败，请重试');
      });
};

// 手机号登录
const handlePhoneLogin = () => {
  if (!phone.value || !/^1[3-9]\d{9}$/.test(phone.value)) {
    alert('请输入正确的手机号');
    return;
  }

  if (!code.value) {
    alert('请输入验证码');
    return;
  }

  const { $axios } = require('@/main').default.config.globalProperties;
  $axios.post('/user/login', {
    phone: phone.value,
    code: code.value
  })
      .then(res => {
        // 后端返回格式调整：{data: {token, user: {id, phone, ...}}}
        const { token, user } = res.data.data;
        if (user && user.id) {
          // 调用创建会话接口获取sessionId
          $axios.post('/user/session', null, {
            params: { userId: user.id }
          }).then(sessionRes => {
            const sessionId = sessionRes.data.data.id;
            store.dispatch('setUserInfo', {
              userId: user.id,
              sessionId,
              phone: user.phone,
              token  // 存储token
            });
            router.push('/user/chat');
          });
        } else {
          alert('验证码错误或用户不存在');
        }
      })
      .catch(err => {
        console.error('登录失败', err);
        alert('登录失败，请重试');
      });
};
</script>

<style scoped>
/* 基础样式 */
.login-container {
  height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
  box-sizing: border-box;
}

.login-card {
  width: 100%;
  background-color: white;
  padding: 30px 20px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  box-sizing: border-box;
}

.login-card h2 {
  text-align: center;
  color: #333;
  margin: 0 0 25px 0;
  font-size: 22px;
}

/* 登录选项容器 */
.login-options {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 登录选项通用样式 */
.login-option {
  padding: 20px;
  border-radius: 12px;
  background-color: #f9f9f9;
}

.option-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  gap: 10px;
}

.option-icon {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #e8f3ff;
  color: #165DFF;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.option-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.option-desc {
  color: #666;
  font-size: 14px;
  margin: 0 0 15px 0;
  line-height: 1.5;
}

.option-btn {
  width: 100%;
  padding: 14px;
  border-radius: 8px;
  border: none;
  background-color: #165DFF;
  color: white;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.option-btn:hover {
  background-color: #0e47d1;
}

/* 分割线 */
.divider {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #ccc;
  font-size: 14px;
}

.divider::before, .divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background-color: #eee;
}

/* 手机号登录表单 */
.phone-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-group {
  width: 100%;
}

.phone-input, .code-input {
  width: 100%;
  padding: 14px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  box-sizing: border-box;
}

.phone-input:focus, .code-input:focus {
  outline: none;
  border-color: #165DFF;
}

.code-group {
  display: flex;
  gap: 10px;
}

.code-input {
  flex: 1;
}

.get-code-btn {
  padding: 0 15px;
  background-color: #f0f2f5;
  border: none;
  border-radius: 8px;
  color: #666;
  cursor: pointer;
  white-space: nowrap;
  font-size: 14px;
}

.get-code-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.phone-login-btn {
  margin-top: 10px;
}

/* 响应式优化 */
@media (max-width: 375px) {
  .login-card {
    padding: 20px 15px;
  }

  .login-option {
    padding: 15px;
  }

  .option-btn {
    padding: 12px;
    font-size: 15px;
  }
}
</style>
